<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>组件间通信</title>
    </head>
    <body>
        <!-- 父组件可以通过props向子组件传递数据 -->
        <!-- 子组件可以通过事件向父组件传递数据 -->
        <div id="app">
            <!-- v-bind的key不支持驼峰命名 -->
            <!-- 可以通过中划线分割 cMovies -> c-movies -->
            <!-- 父组件接收自定义事件 item-click 完成参数接收 -->
            <cpn :cmovies="movies" @item-click="cpnClick"></cpn>
        </div>
    </body>
    <template id="cpn">
        <div>
            <h2>父组件</h2>
            <ul>
                <li v-for="category in categories" @click="itemClick(category)">{{category.name}}</li>
            </ul>
            <tag v-for="movie in cmovies" :key="movie" :cmovie="movie"></tag>
            <!-- 使用默认值 -->
            <tag></tag>
        </div>
    </template>
    <template id="tag">
        <p style="color: yellow">{{cmovie}}</p>
    </template>
    <script src="../../js/vue.js" charset="utf-8"></script>
    <script type="text/javascript">
        const tag = Vue.component("tag", {
            template: "#tag",
            props: {
                cmovie: {
                    type: String,
                    default: '西虹市首富',
                    required: false // true 表示必传, 如果没有传 console 会报错
                }
            },
            data() {
                return {};
            }
        });

        const cpn = Vue.component('cpn', {
            template: "#cpn",
            // props: ['cmovies'],
            props: {
                cmovies: {
                    type: Array,
                    // default 属性如果是 对象 或者 数组， 默认值可以是函数(工厂方法)
                    default: [],
                    // default: () => [],
                    validator: value => true // 验证输入的值
                }

            },
            data() {
                return {
                    categories: [
                        {id: '101', name:'热门推荐'},
                        {id: '102', name:'手机数码'},
                        {id: '103', name:'家用家电'},
                        {id: '104', name:'电脑办公'},
                        {id: '105', name:'日用品'}
                    ]
                };
            },
            methods: {
                itemClick(category) {
                    console.log('子组件参数', category);
                    this.$emit('item-click', category); // 子组件想父组件传递事件和数据
                }
            },
            components: {
                tag
            }
        });

        const app = new Vue({
            el: '#app',
            data: {
                message: '你好啊',
                movies: ['海王', '复仇者联盟', '夏洛特烦恼']
            },
            methods: {
                cpnClick(category) {
                    console.log("父组件接收参数 ", category.name)
                }
            },
            components: {
                cpn
            }
        });
    </script>
</html>
